<?php
class LoginForm extends sfForm
{
	public function configure()
	{
		$this->setWidgets(array(
      'username' => new sfWidgetFormInput(), 
      'password' => new sfWidgetFormInputPassword() 
		));

		$this->validatorSchema['username'] = new sfValidatorString(array('required' => true), array('required' => 'you must enter your username'));
		$this->validatorSchema['password'] = new sfValidatorString(array('required' => true), array('required' => 'you must enter your username'));

		$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this,'checkUser'))));
		$this->widgetSchema->getNameFormat('user[%s]');
	}
	public function checkUser($validator, $values){
		if($values['username'] && $values['password']){
			$currUser = sfContext::getInstance()->getRequest()->getParameter('user');
			$oUser = Doctrine_Core::getTable('User')->findOneByUsernameAndPassword($values['username'],$values['password']);
			if($oUser){
				if(sfContext::getInstance()->getUser()->isAuthenticated()){
					sfContext::getInstance()->getUser()->getAttributeHolder()->removeNamespace('ns_user');
					sfContext::getInstance()->getUser()->setAuthenticated(false);
					sfContext::getInstance()->getUser()->clearCredentials();
				}

				sfContext::getInstance()->getUser()->setAuthenticated(true);

				sfContext::getInstance()->getUser()->setAttribute('id', $oUser->getId(),'ns_user');
				sfContext::getInstance()->getUser()->setAttribute('id', $oUser->getName(),'ns_user');
				sfContext::getInstance()->getUser()->addCredential('user');
			}
			else{
				$error = new sfValidatorError($validator,'wrong username or password');
				throw new sfValidatorErrorSchema($validator,array('username'=>$error));
			}
		}
		return $values;
	}
}